// cspell:disable

// API 控制器
// [controller] 占位符会自动替换为控制器名称（去掉 "Controller" 后缀）
// PUT：更新完整资源
// POST：创建新资源
// PATCH：部分更新资源

namespace mrs;

using System.ComponentModel;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
[Description("http://localhost:5000/api/meteor")]
public partial class MeteorController : ControllerBase
{
    private readonly ILogger<MeteorController> _logger;
    private readonly IMeteorService _meteorService;

    /// <summary>
    /// 使用依赖注入 (Dependency Injection) 模式 (控制器只处理 HTTP 相关逻辑，e.g. IMeteorService, 业务逻辑在服务层)
    /// </summary>
    /// <param name="logger"> 泛型接口，指定了日志来源为 MeteorController </param>
    /// <param name="meteorService"> 提供业务逻辑服务 </param>
    public MeteorController(ILogger<MeteorController> logger, IMeteorService meteorService)
    {
        _logger = logger;
        _meteorService = meteorService;

        _logger.LogInformation("--- MeteorController construtor...");


        /*
        // 单元测试时可以注入 Mock 服务
        var mockLogger = new Mock<ILogger<MeteorController>>();
        var mockService = new Mock<IMeteorService>();
        var controller = new MeteorController(mockLogger.Object, mockService.Object);
        */
    }

    // {{END}}
}

// GET
partial class MeteorController
{
    /// <summary>
    /// API Meteor ABC
    /// </summary>
    /// <returns></returns>
    /// <remarks>补充信息
    /// <![CDATA[ 
    /// HTTP GET 请求: /api/meteor
    /// ]]>
    /// </remarks>
    [HttpGet]
    public async Task<IActionResult> GetMeteor()
    {
        var result = await _meteorService.Test(); 

        return Ok(new
        {
            status = "Meteor Radar Service is Running",
            currentTime = DateTime.Now,
            meteorSettings=result,
        });
    }

    /// <summary>
    /// 处理天气雷达基数据
    /// </summary>
    /// <param name="dataCode"> 天气雷达数据代码 </param>
    /// <param name="drawParam"> 其他参数 </param>
    /// <example>代码示例</example>
    /// <returns> </returns>
    /// <remarks>补充信息
    /// <![CDATA[ 
    /// HTTP GET 请求: /api/meteor/process?dataCode=cref&drawParam=cil
    /// ]]>
    /// </remarks>
    [HttpGet("process")]
    public async Task<ActionResult<MeteorResult>> ProcessMeteorData([FromQuery] string dataCode, [FromQuery] string drawParam = "")
    {
        try
        {
            // _logger.LogInformation("--- Processing meteor data - DataCode: {DataCode}, OtherParam: {OtherParam}", dataCode, drawParam);
            
            // SemaphoreSlim s;
            // 多并发处理 + 
            // 架构层次与并发策略
            // 电商平台高并发处理要点：
            // 分层限流：网关层、服务层、方法层
            // 异步化：消息队列削峰填谷
            // 缓存策略：多级缓存减少数据库压力
            // 原子操作：Redis Lua脚本保证数据一致性
            // 熔断降级：防止雪崩效应
            // 监控告警：实时发现性能瓶颈
            // 数据库优化：读写分离、连接池、索引优化

            var result = await _meteorService.GetMetradProductAsync(dataCode, drawParam);

            if (result.Success)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }
        catch (Exception ex)
        {
            // _logger.LogError(ex, "Error processing meteor data");
            return StatusCode(500, new { error = ex.Message });
        }
    }

    [HttpGet("output")]
    public ActionResult GetOutputFile()
    {
        try
        {
            string outputPath = "/home/shenyc/temp/out.json";

            if (!System.IO.File.Exists(outputPath))
            {
                return NotFound(new { error = "Output file not found" });
            }

            var fileContent = System.IO.File.ReadAllText(outputPath);
            return Content(fileContent, "application/json");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error reading output file");
            return StatusCode(500, new { error = ex.Message });
        }
    }

    // {{END}}
}

// POST
partial class MeteorController
{
    // HTTP POST 请求
    // POST /api/meteor/process
    // Content-Type: application/json
    // {
    //     "dataCode": "a",
    //     "otherParam": "_param"
    // }
    // [HttpPost("process")]
    // public async Task<ActionResult<MeteorResult>> ProcessMeteorData([FromBody] MeteorRequest request)
    // {
    //     try
    //     {
    //         _logger.LogInformation("--- Processing meteor data request: {@Request}", request);

    //         var result = await _meteorService.GetMeteorDataAsync(request.DataCode, request.OtherParam);

    //         if (result.Success)
    //         {
    //             return Ok(result);
    //         }
    //         else
    //         {
    //             return BadRequest(result);
    //         }
    //     }
    //     catch (Exception ex)
    //     {
    //         _logger.LogError(ex, "Error processing meteor data request");
    //         return StatusCode(500, new { error = ex.Message });
    //     }
    // }

    // {{END}}
}
